package com.web.utils;

import com.web.entity.AMapCity;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class GetLocation {


//        public static void main(String[] args) {
//            try {
//                String[] coordinate = getCoordinate("杭州市");
//                String s = coordinate[0];
//                String ss = coordinate[1];
//                System.out.println(s);//0:经度 1:纬度
//                System.out.println(ss);//0:经度 1:纬度
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }


        /**
         * 根据城市名称查询所在经纬度
         * @param addr
         * 查询的地址
         * @return
         * @throws IOException
         */
        public static String[] getCoordinate(String addr) throws IOException {
            String lng = null;//经度
            String lat = null;//纬度
            String address = null;
            try {
                address = java.net.URLEncoder.encode(addr, "UTF-8");
            }catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            String key = "NcMnc56RX48MjpsOfP4ZEW5GVHmCCmeg";
            String url = String .format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
            URL myURL = null;
            URLConnection httpsConn = null;
            try {
                myURL = new URL(url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            InputStreamReader insr = null;
            BufferedReader br = null;
            try {
                httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
                if (httpsConn != null) {
                    insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
                    br = new BufferedReader(insr);
                    String data = null;
                    int count = 1;
                    while((data= br.readLine())!=null){
                        if(count==5){
                            lng = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
                            count++;
                        }else if(count==6){
                            lat = data.substring(data.indexOf(":")+1);//纬度
                            count++;
                        }else{
                            count++;
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(insr!=null){
                    insr.close();
                }
                if(br!=null){
                    br.close();
                }
            }
            return new String[]{lng,lat};
        }

    /**
     * 根据经纬度查询城市名
     * @param log
     * @param lat
     * @return
     */
    public static String getAdd(String log, String lat ){
        //lat 小  log  大
        //参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
//        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l="+lat+","+log+"&type=010";
        String urlString = "http://restapi.amap.com/v3/geocode/regeo?" +
                "key=c6900a31e9bdfd0a479f66052c3ae73c&location="+log+","+lat;
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error in wapaction,and e is " + e.getMessage());
        }
        System.out.println("定位地址:"+res);

        return res;
    }
    /**
     * 经纬度获取城市名
     * @param add
     * @return
     */
    public static String getCityName(String add){
        if (StringUtils.isBlank(add)){
            return "未知";
        }
//        JSONObject jsonObject = JSONObject.fromObject(add);
//        JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("addrList"));
//        JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));
//        String allAdd = j_2.getString("admName");
//        String arr[] = allAdd.split(",");
//        System.out.println("address :" + arr[2]);
//        return arr[2];

        JSONObject jsonObject = JSONObject.fromObject(add);
        AMapCity stu=(AMapCity)JSONObject.toBean(jsonObject, AMapCity.class);
        return stu.getRegeocode().getAddressComponent().getDistrict();
    }




}

